package com.hs.srm.admin.modules.harmfulsubstance.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hs.srm.admin.modules.harmfulsubstance.dao.EnvironCommitmentDao;
import com.hs.srm.admin.modules.harmfulsubstance.entity.EnvironCommitmentEntity;
import com.hs.srm.admin.modules.harmfulsubstance.service.EnvironCommitmentService;
import com.hs.srm.admin.modules.notice.dictionary.NoticeKind;
import com.hs.srm.admin.modules.notice.service.NoticeMainInfoService;
import com.hs.srm.admin.modules.vendor.vo.VendorCertificateVO;
import com.hs.srm.base.common.config.SysConfig;
import com.hs.srm.base.common.utils.QueryParam;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.hs.srm.tools.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * (EnvironCommitment)表服务实现类
 *
 * @author ych
 * @since 2020-03-05 14:25:17
 */
@Service("environCommitmentService")
public class EnvironCommitmentServiceImpl extends ServiceImpl<EnvironCommitmentDao, EnvironCommitmentEntity> implements EnvironCommitmentService {

    @Resource
    private EnvironCommitmentDao environCommitmentDao;

    @Autowired
    private NoticeMainInfoService noticeMainInfoService;

    /**
     * 列表数据查询
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //类别
        String type = (String) params.get("type");

        //有效状态 : 1，有效；-1，无效
        String validStatus = (String) params.get("validStatus");

        //审核状态 : 1，已审核；-1，未审核
        String reviewStatus = (String) params.get("reviewStatus");

        //供应商账号
        String vendorCode = (String) params.get("username");

        /**
         * 当前日期年份减一，用于判断是否失效
         * contract_date < date : 失效
         * contract_date > date : 有效
         */
        LocalDate date = LocalDate.now().minusYears(1);

        //查询录入开始日期
        String startDate = (String) params.get("startDate");
        //查询录入结束日期
        String endDate = (String) params.get("endDate");

        Page page = this.selectPage(new QueryParam<EnvironCommitmentEntity>(params).getPage(),
                new EntityWrapper<EnvironCommitmentEntity>()
                        .eq(StringUtils.isNotBlank(type), "type", type)
                        .eq(StringUtils.isNotBlank(vendorCode), "vendor_code", vendorCode)
                        //有效状态不空，且为有效，查询合同签订日期不超过一年且为有效的数据
                        .gt(StringUtils.isNotBlank(validStatus) && validStatus.equals("1"), "contract_date", date)
                        .ne(StringUtils.isNotBlank(validStatus) && validStatus.equals("1"), "valid_status", "-1")
                        //有效状态不空，且为无效
                        .eq(StringUtils.isNotBlank(validStatus) && validStatus.equals("-1"), "valid_status", validStatus)
                        .ge(StringUtils.isNotBlank(startDate), "edit_date", startDate)
                        .le(StringUtils.isNotBlank(endDate), "edit_date", endDate)
                        .andNew(StringUtils.isNotBlank(reviewStatus) && reviewStatus.equals("1"), "reviewer is not null")
                        .andNew(StringUtils.isNotBlank(reviewStatus) && reviewStatus.equals("-1"), "reviewer is null")
                        .orderBy("edit_date", false)
        );

        return new PageUtils(page);
    }

    /**
     * @param entity     前端映射实体
     * @param request
     * @param sapCode    登录者账号
     * @param vendorName
     * @return
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public R save(EnvironCommitmentEntity entity, HttpServletRequest request, String sapCode, String vendorName) throws IOException, ServletException {
        Part part = request.getPart("attachFile");
        //文件保存路径
        String fileDir = SysConfig.getUploadPath() + "/harmfulsubstance/";
        //添加时间后缀 _yyyyMMddHHmmss
        String newFileName = FileUtils.addDateTimeSuffix(part.getSubmittedFileName());
        try {
            //保存文件
            FileUtils.fileUpload(fileDir, newFileName, part);

            //上传文件路径
            entity.setAttach("/harmfulsubstance/" + newFileName);
            //录入状态，1：已提交
            entity.setEditStatus(1);
            //创建时间
            entity.setCreateDate(new Date());
            //录入日期
            entity.setEditDate(new Date());
            //创建人
            entity.setCreator(sapCode);
            //供应商编码、名称
            entity.setVendorCode(sapCode);
            entity.setVendorName(vendorName);
            environCommitmentDao.insert(entity);

            //通知品质专员
            String content = entity.getVendorName() + " 已填写环保承诺书 ！";
            noticeMainInfoService.saveNotice(NoticeKind.KindEnum.PZYCD, content);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error();
        }
        return R.ok();
    }

    @Override
    public List<VendorCertificateVO> findFilePath(String vendorCode) {
        return this.environCommitmentDao.findFilePath(vendorCode);
    }
}